home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 1998 November / IRIX 6.5.2 Base Documentation November 1998.img / usr / share / catman / u_man / cat1 / perlmod.z / perlmod
Text File  |  1998-10-30  |  20KB  |  529 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlmod - Perl modules (packages and symbol tables)
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      PPPPaaaacccckkkkaaaaggggeeeessss
  13.  
  14.      Perl provides a mechanism for alternative namespaces to protect packages
  15.      from stomping on each other's variables.  In fact, apart from certain
  16.      magical variables, there's really no such thing as a global variable in
  17.      Perl.  The package statement declares the compilation unit as being in
  18.      the given namespace.  The scope of the package declaration is from the
  19.      declaration itself through the end of the enclosing block, eval, sub, or
  20.      end of file, whichever comes first (the same scope as the _m_y() and
  21.      _l_o_c_a_l() operators).  All further unqualified dynamic identifiers will be
  22.      in this namespace.  A package statement affects only dynamic variables--
  23.      including those you've used _l_o_c_a_l() on--but _n_o_t lexical variables created
  24.      with _m_y().  Typically it would be the first declaration in a file to be
  25.      included by the require or use operator.  You can switch into a package
  26.      in more than one place; it influences merely which symbol table is used
  27.      by the compiler for the rest of that block.  You can refer to variables
  28.      and filehandles in other packages by prefixing the identifier with the
  29.      package name and a double colon: $Package::Variable.  If the package name
  30.      is null, the main package is assumed.  That is, $::sail is equivalent to
  31.      $main::sail.
  32.  
  33.      (The old package delimiter was a single quote, but double colon is now
  34.      the preferred delimiter, in part because it's more readable to humans,
  35.      and in part because it's more readable to eeeemmmmaaaaccccssss macros.  It also makes
  36.      C++ programmers feel like they know what's going on.)
  37.  
  38.      Packages may be nested inside other packages: $OUTER::INNER::var.  This
  39.      implies nothing about the order of name lookups, however.  All symbols
  40.      are either local to the current package, or must be fully qualified from
  41.      the outer package name down.  For instance, there is nowhere within
  42.      package OUTER that $INNER::var refers to $OUTER::INNER::var.  It would
  43.      treat package INNER as a totally separate global package.
  44.  
  45.      Only identifiers starting with letters (or underscore) are stored in a
  46.      package's symbol table.  All other symbols are kept in package main,
  47.      including all of the punctuation variables like $_.  In addition, the
  48.      identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are
  49.      forced to be in package main, even when used for other purposes than
  50.      their builtin one.  Note also that, if you have a package called m, s, or
  51.      y, then you can't use the qualified form of an identifier because it will
  52.      be interpreted instead as a pattern match, a substitution, or a
  53.      translation.
  54.  
  55.      (Variables beginning with underscore used to be forced into package main,
  56.      but we decided it was more useful for package writers to be able to use
  57.      leading underscore to indicate private variables and method names.  $_ is
  58.      still global though.)
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  71.  
  72.  
  73.  
  74.      _E_v_a_l()ed strings are compiled in the package in which the _e_v_a_l() was
  75.      compiled.  (Assignments to $SIG{}, however, assume the signal handler
  76.      specified is in the main package.  Qualify the signal handler name if you
  77.      wish to have a signal handler in a package.)  For an example, examine
  78.      _p_e_r_l_d_b._p_l in the Perl library.  It initially switches to the DB package
  79.      so that the debugger doesn't interfere with variables in the script you
  80.      are trying to debug.  At various points, however, it temporarily switches
  81.      back to the main package to evaluate various expressions in the context
  82.      of the main package (or wherever you came from).  See the _p_e_r_l_d_e_b_u_g
  83.      manpage.
  84.  
  85.      The special symbol __PACKAGE__ contains the current package, but cannot
  86.      (easily) be used to construct variables.
  87.  
  88.      See the _p_e_r_l_s_u_b manpage for other scoping issues related to _m_y() and
  89.      _l_o_c_a_l(), and the _p_e_r_l_r_e_f manpage regarding closures.
  90.  
  91.      SSSSyyyymmmmbbbboooollll TTTTaaaabbbblllleeeessss
  92.  
  93.      The symbol table for a package happens to be stored in the hash of that
  94.      name with two colons appended.  The main symbol table's name is thus
  95.      %main::, or %:: for short.  Likewise symbol table for the nested package
  96.      mentioned earlier is named %OUTER::INNER::.
  97.  
  98.      The value in each entry of the hash is what you are referring to when you
  99.      use the *name typeglob notation.  In fact, the following have the same
  100.      effect, though the first is more efficient because it does the symbol
  101.      table lookups at compile time:
  102.  
  103.          local *main::foo    = *main::bar;
  104.          local $main::{foo}  = $main::{bar};
  105.  
  106.      You can use this to print out all the variables in a package, for
  107.      instance.  Here is _d_u_m_p_v_a_r._p_l from the Perl library:
  108.  
  109.         package dumpvar;
  110.         sub main::dumpvar {
  111.             ($package) = @_;
  112.             local(*stab) = eval("*${package}::");
  113.             while (($key,$val) = each(%stab)) {
  114.                 local(*entry) = $val;
  115.                 if (defined $entry) {
  116.                     print "\$$key = '$entry'\n";
  117.                 }
  118.  
  119.                 if (defined @entry) {
  120.                     print "\@$key = (\n";
  121.                     foreach $num ($[ .. $#entry) {
  122.                         print "  $num\t'",$entry[$num],"'\n";
  123.                     }
  124.                     print ")\n";
  125.                 }
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  137.  
  138.  
  139.  
  140.                 if ($key ne "${package}::" && defined %entry) {
  141.                     print "\%$key = (\n";
  142.                     foreach $key (sort keys(%entry)) {
  143.                         print "  $key\t'",$entry{$key},"'\n";
  144.                     }
  145.                     print ")\n";
  146.                 }
  147.             }
  148.         }
  149.  
  150.      Note that even though the subroutine is compiled in package dumpvar, the
  151.      name of the subroutine is qualified so that its name is inserted into
  152.      package main.  While popular many years ago, this is now considered very
  153.      poor style; in general, you should be writing modules and using the
  154.      normal export mechanism instead of hammering someone else's namespace,
  155.      even main's.
  156.  
  157.      Assignment to a typeglob performs an aliasing operation, i.e.,
  158.  
  159.          *dick = *richard;
  160.  
  161.      causes variables, subroutines, and file handles accessible via the
  162.      identifier richard to also be accessible via the identifier dick.  If you
  163.      want to alias only a particular variable or subroutine, you can assign a
  164.      reference instead:
  165.  
  166.          *dick = \$richard;
  167.  
  168.      makes $richard and $dick the same variable, but leaves @richard and @dick
  169.      as separate arrays.  Tricky, eh?
  170.  
  171.      This mechanism may be used to pass and return cheap references into or
  172.      from subroutines if you won't want to copy the whole thing.
  173.  
  174.          %some_hash = ();
  175.          *some_hash = fn( \%another_hash );
  176.          sub fn {
  177.              local *hashsym = shift;
  178.              # now use %hashsym normally, and you
  179.              # will affect the caller's %another_hash
  180.              my %nhash = (); # do what you want
  181.              return \%nhash;
  182.          }
  183.  
  184.      On return, the reference will overwrite the hash slot in the symbol table
  185.      specified by the *some_hash typeglob.  This is a somewhat tricky way of
  186.      passing around references cheaply when you won't want to have to remember
  187.      to dereference variables explicitly.
  188.  
  189.      Another use of symbol tables is for making "constant"  scalars.
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  203.  
  204.  
  205.  
  206.          *PI = \3.14159265358979;
  207.  
  208.      Now you cannot alter $PI, which is probably a good thing all in all.
  209.      This isn't the same as a constant subroutine (one prototyped to take no
  210.      arguments and to return a constant expression), which is subject to
  211.      optimization at compile-time.  This isn't.  See the _p_e_r_l_s_u_b manpage for
  212.      details on these.
  213.  
  214.      You can say *foo{PACKAGE} and *foo{NAME} to find out what name and
  215.      package the *foo symbol table entry comes from.  This may be useful in a
  216.      subroutine which is passed typeglobs as arguments
  217.  
  218.          sub identify_typeglob {
  219.              my $glob = shift;
  220.              print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n";
  221.          }
  222.          identify_typeglob *foo;
  223.          identify_typeglob *bar::baz;
  224.  
  225.      This prints
  226.  
  227.          You gave me main::foo
  228.          You gave me bar::baz
  229.  
  230.      The *foo{THING} notation can also be used to obtain references to the
  231.      individual elements of *foo, see the _p_e_r_l_r_e_f manpage.
  232.  
  233.      PPPPaaaacccckkkkaaaaggggeeee CCCCoooonnnnssssttttrrrruuuuccccttttoooorrrrssss aaaannnndddd DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  234.  
  235.      There are two special subroutine definitions that function as package
  236.      constructors and destructors.  These are the BEGIN and END routines.  The
  237.      sub is optional for these routines.
  238.  
  239.      A BEGIN subroutine is executed as soon as possible, that is, the moment
  240.      it is completely defined, even before the rest of the containing file is
  241.      parsed.  You may have multiple BEGIN blocks within a file--they will
  242.      execute in order of definition.  Because a BEGIN block executes
  243.      immediately, it can pull in definitions of subroutines and such from
  244.      other files in time to be visible to the rest of the file.  Once a BEGIN
  245.      has run, it is immediately undefined and any code it used is returned to
  246.      Perl's memory pool.  This means you can't ever explicitly call a BEGIN.
  247.  
  248.      An END subroutine is executed as late as possible, that is, when the
  249.      interpreter is being exited, even if it is exiting as a result of a _d_i_e()
  250.      function.  (But not if it's is being blown out of the water by a
  251.      signal--you have to trap that yourself (if you can).)  You may have
  252.      multiple END blocks within a file--they will execute in reverse order of
  253.      definition; that is: last in, first out (LIFO).
  254.  
  255.      Inside an END subroutine $? contains the value that the script is going
  256.      to pass to exit().  You can modify $? to change the exit value of the
  257.      script.  Beware of changing $? by accident (e.g. by running something via
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  269.  
  270.  
  271.  
  272.      system).
  273.  
  274.      Note that when you use the ----nnnn and ----pppp switches to Perl, BEGIN and END work
  275.      just as they do in aaaawwwwkkkk, as a degenerate case.
  276.  
  277.      PPPPeeeerrrrllll CCCCllllaaaasssssssseeeessss
  278.  
  279.      There is no special class syntax in Perl, but a package may function as a
  280.      class if it provides subroutines that function as methods.  Such a
  281.      package may also derive some of its methods from another class package by
  282.      listing the other package name in its @ISA array.
  283.  
  284.      For more on this, see the _p_e_r_l_t_o_o_t manpage and the _p_e_r_l_o_b_j manpage.
  285.  
  286.      PPPPeeeerrrrllll MMMMoooodddduuuulllleeeessss
  287.  
  288.      A module is just a package that is defined in a library file of the same
  289.      name, and is designed to be reusable.  It may do this by providing a
  290.      mechanism for exporting some of its symbols into the symbol table of any
  291.      package using it.  Or it may function as a class definition and make its
  292.      semantics available implicitly through method calls on the class and its
  293.      objects, without explicit exportation of any symbols.  Or it can do a
  294.      little of both.
  295.  
  296.      For example, to start a normal module called Some::Module, create a file
  297.      called Some/Module.pm and start with this template:
  298.  
  299.          package Some::Module;  # assumes Some/Module.pm
  300.  
  301.          use strict;
  302.  
  303.          BEGIN {
  304.              use Exporter   ();
  305.              use vars       qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
  306.  
  307.              # set the version for version checking
  308.              $VERSION     = 1.00;
  309.              # if using RCS/CVS, this may be preferred
  310.              $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
  311.  
  312.              @ISA         = qw(Exporter);
  313.              @EXPORT      = qw(&func1 &func2 &func4);
  314.              %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
  315.  
  316.              # your exported package globals go here,
  317.              # as well as any optionally exported functions
  318.              @EXPORT_OK   = qw($Var1 %Hashit &func3);
  319.          }
  320.          use vars      @EXPORT_OK;
  321.  
  322.          # non-exported package globals go here
  323.          use vars      qw(@more $stuff);
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  335.  
  336.  
  337.  
  338.          # initalize package globals, first exported ones
  339.          $Var1   = '';
  340.          %Hashit = ();
  341.  
  342.          # then the others (which are still accessible as $Some::Module::stuff)
  343.          $stuff  = '';
  344.          @more   = ();
  345.  
  346.          # all file-scoped lexicals must be created before
  347.          # the functions below that use them.
  348.  
  349.          # file-private lexicals go here
  350.          my $priv_var    = '';
  351.          my %secret_hash = ();
  352.  
  353.          # here's a file-private function as a closure,
  354.          # callable as &$priv_func;  it cannot be prototyped.
  355.          my $priv_func = sub {
  356.              # stuff goes here.
  357.          };
  358.  
  359.          # make all your functions, whether exported or not;
  360.          # remember to put something interesting in the {} stubs
  361.          sub func1      {}    # no prototype
  362.          sub func2()    {}    # proto'd void
  363.          sub func3($$)  {}    # proto'd to 2 scalars
  364.  
  365.          # this one isn't exported, but could be called!
  366.          sub func4(\%)  {}    # proto'd to 1 hash ref
  367.  
  368.          END { }       # module clean-up code here (global destructor)
  369.  
  370.      Then go on to declare and use your variables in functions without any
  371.      qualifications.  See the _E_x_p_o_r_t_e_r manpage and the the _p_e_r_l_m_o_d_l_i_b manpage
  372.      for details on mechanics and style issues in module creation.
  373.  
  374.      Perl modules are included into your program by saying
  375.  
  376.          use Module;
  377.  
  378.      or
  379.  
  380.          use Module LIST;
  381.  
  382.      This is exactly equivalent to
  383.  
  384.          BEGIN { require "Module.pm"; import Module; }
  385.  
  386.      or
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  401.  
  402.  
  403.  
  404.          BEGIN { require "Module.pm"; import Module LIST; }
  405.  
  406.      As a special case
  407.  
  408.          use Module ();
  409.  
  410.      is exactly equivalent to
  411.  
  412.          BEGIN { require "Module.pm"; }
  413.  
  414.      All Perl module files have the extension ._p_m.  use assumes this so that
  415.      you don't have to spell out "_M_o_d_u_l_e._p_m" in quotes.  This also helps to
  416.      differentiate new modules from old ._p_l and ._p_h files.  Module names are
  417.      also capitalized unless they're functioning as pragmas, "Pragmas" are in
  418.      effect compiler directives, and are sometimes called "pragmatic modules"
  419.      (or even "pragmata" if you're a classicist).
  420.  
  421.      Because the use statement implies a BEGIN block, the importation of
  422.      semantics happens at the moment the use statement is compiled, before the
  423.      rest of the file is compiled.  This is how it is able to function as a
  424.      pragma mechanism, and also how modules are able to declare subroutines
  425.      that are then visible as list operators for the rest of the current file.
  426.      This will not work if you use require instead of use.  With require you
  427.      can get into this problem:
  428.  
  429.          require Cwd;                # make Cwd:: accessible
  430.          $here = Cwd::getcwd();
  431.  
  432.          use Cwd;                    # import names from Cwd::
  433.          $here = getcwd();
  434.  
  435.          require Cwd;                # make Cwd:: accessible
  436.          $here = getcwd();           # oops! no main::getcwd()
  437.  
  438.      In general use Module (); is recommended over require Module;.
  439.  
  440.      Perl packages may be nested inside other package names, so we can have
  441.      package names containing ::.  But if we used that package name directly
  442.      as a filename it would makes for unwieldy or impossible filenames on some
  443.      systems.  Therefore, if a module's name is, say, Text::Soundex, then its
  444.      definition is actually found in the library file _T_e_x_t/_S_o_u_n_d_e_x._p_m.
  445.  
  446.      Perl modules always have a ._p_m file, but there may also be dynamically
  447.      linked executables or autoloaded subroutine definitions associated with
  448.      the module.  If so, these will be entirely transparent to the user of the
  449.      module.  It is the responsibility of the ._p_m file to load (or arrange to
  450.      autoload) any additional functionality.  The POSIX module happens to do
  451.      both dynamic loading and autoloading, but the user can say just use POSIX
  452.      to get it all.
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))                                                          PPPPEEEERRRRLLLLMMMMOOOODDDD((((1111))))
  467.  
  468.  
  469.  
  470.      For more information on writing extension modules, see the _p_e_r_l_x_s_t_u_t
  471.      manpage and the _p_e_r_l_g_u_t_s manpage.
  472.  
  473. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  474.      See the _p_e_r_l_m_o_d_l_i_b manpage for general style issues related to building
  475.      Perl modules and classes as well as descriptions of the standard library
  476.      and CPAN, the _E_x_p_o_r_t_e_r manpage for how Perl's standard import/export
  477.      mechanism works, the _p_e_r_l_t_o_o_t manpage for an in-depth tutorial on
  478.      creating classes, the _p_e_r_l_o_b_j manpage for a hard-core reference document
  479.      on objects, and the _p_e_r_l_s_u_b manpage for an explanation of functions and
  480.      scoping.
  481.  
  482.  
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.